package com.young.aidl_base_sdk.bean;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import com.young.aidl_base_sdk.ICalculator;
import com.young.aidl_base_sdk.ICalculatorListener;

import java.util.concurrent.CountDownLatch;

/**
 * Author：young
 * .
 * Time： 17/9/2023 PM1:29 Sun
 * .
 * Desc：通讯管理器
 */
public class MsgManager {

    public static final String TAG = "Young-AIDL-Client-" + MsgManager.class.getSimpleName();

    // AIDL 接口
    private volatile ICalculator mCalculator;

    private Handler mHandler = new Handler(Looper.getMainLooper());


    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 将 IBinder 转为具体的 AIDL 接口
            mCalculator = ICalculator.Stub.asInterface(service);
            Log.e(TAG, "onServiceConnected: 连接服务成功 " + name + "=" + service);
            Log.e(TAG, "getCalculator: hllo" + mCalculator);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mCalculator = null;
            Log.e(TAG, "onServiceDisconnected: 服务连接断开了 " + name);
        }
    };


    /**
     * 绑定服务
     *
     * @param context 上下文
     */
    public Boolean bindService(Context context) {
        Intent intent = new Intent();
        intent.setAction("com.young.CUSTOMER_SERVICE");
        intent.setComponent(new ComponentName("com.young.aidl_base_server",
                "com.young.aidl_base_server.CalculatorService"));
        boolean connected = context.bindService(intent, mServiceConnection, Activity.BIND_AUTO_CREATE);
        Log.e(TAG, "bindService: " + connected);
        return connected;
    }


    public ICalculator getCalculator() {
        return mCalculator;
    }

    public void getCalculator(Context context, OnGetCalculatorListener listener) {
        if (mCalculator == null) {
            long start = System.currentTimeMillis();
            new Thread() {
                @Override
                public void run() {
                    int retryCount1 = 5;

                    while (true) {
                        boolean connected = bindService(context);
                        if (connected) {
                            int retryCount = 5;
                            while (mCalculator == null) {
                                try {
                                    Thread.sleep(50);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                retryCount--;
                                if (retryCount <= 0) {
                                    break;
                                }
                            }
                        }

                        if (mCalculator != null) {
                            Log.e(TAG, "run: " + (System.currentTimeMillis() - start) + " ms");
                            runOnUI(() -> listener.onGet(mCalculator));
                            break;
                        }

                        retryCount1--;
                        if (retryCount1 <= 0) {
                            break;
                        }
                    }
                }
            }.start();

        } else {
            listener.onGet(mCalculator);
        }
    }


    public void runOnUI(Runnable runnable) {
        mHandler.post(runnable);
    }

    public interface OnGetCalculatorListener {
        void onGet(ICalculator calculator);
    }
}
